package com.platform.comm.common.service;

import com.platform.comm.service.ICommBatchInfoBiz;
import com.platform.comm.common.batch.ComBatchExportContext;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * description: 通用批量导出下载操作
 *
 * @author lch
 */
@Service
@Scope("prototype")
public class ComBatchExportService {
    private JobLauncher jobLauncher;

    private Job comExportJob;
    private ComBatchExportContext comBatchExportContext;
    private ICommBatchInfoBiz commBatchInfoBiz;

    public ComBatchExportService(JobLauncher jobLauncher, Job comExportJob,
                                 ComBatchExportContext comBatchExportContext, ICommBatchInfoBiz commBatchInfoBiz) {
        this.jobLauncher = jobLauncher;
        this.comExportJob = comExportJob;
        this.comBatchExportContext = comBatchExportContext;
        this.commBatchInfoBiz = commBatchInfoBiz;
    }

    public void startExportJob(Map<String, String> parameterMap) throws Exception {
        initExportContext(parameterMap);
        JobExecution jobExecution = jobLauncher.run(comExportJob, buildExportJobParameters());
        jobExecution.getExecutionContext().put("config", comBatchExportContext);
        if (jobExecution.getStatus().isRunning()) {
            // 保存状态
            commBatchInfoBiz.createExportDirJob(comBatchExportContext.getNewExportJob(jobExecution.getJobId()));
        }
    }

    private JobParameters buildExportJobParameters() {
        return new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .toJobParameters();
    }

    private void initExportContext(Map<String, String> parameterMap) {
        comBatchExportContext
                .buildConfig(parameterMap.get("moduleName"))
                .bindParameterMap(parameterMap)
                .build();
    }
}
